package com.market.domain.award.service.distribute.impl;

import com.market.domain.award.model.aggregate.GiveOutPrizesAggregate;
import com.market.domain.award.model.entity.DistributeAwardEntity;
import com.market.domain.award.model.entity.UserAwardRecordEntity;
import com.market.domain.award.model.entity.UserCreditAwardEntity;
import com.market.domain.award.model.valobj.AwardStateVO;
import com.market.domain.award.repository.IAwardRepository;
import com.market.domain.award.service.distribute.IDistributeAward;
import com.market.types.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;

@Component("user_credit_random")
public class UserCreditRandomAward implements IDistributeAward {

    @Resource
    private IAwardRepository repository;

    @Override
    public void giveOutPrizes(DistributeAwardEntity distributeAwardEntity) {
        //拿到奖品id
        Integer awardId = distributeAwardEntity.getAwardId();
        String awardConfig = distributeAwardEntity.getAwardConfig();

        //说明没透传，主动去数据库查询
        if(StringUtils.isBlank(awardConfig)){
            //查询奖品配置如：1,100
            awardConfig = repository.queryAwardConfig(awardId);
        }

        //生成随机积分
        String[] creditRange = awardConfig.split(Constants.SPLIT);
        if(creditRange.length != 2)
            throw new RuntimeException("award_config 「" + awardConfig + "」配置不是一个范围值，如 1,100");

        //生成随机积分值
        Float creditAmount = generateRandom(Float.valueOf(creditRange[0]), Float.valueOf(creditRange[1]));

        //构建聚合对象
        UserAwardRecordEntity userAwardRecordEntity = GiveOutPrizesAggregate.buildDistributeUserAwardRecordEntity(
                distributeAwardEntity.getUserId(),
                distributeAwardEntity.getOrderId(),
                awardId,
                AwardStateVO.complete
        );
        UserCreditAwardEntity userCreditAwardEntity = GiveOutPrizesAggregate.buildUserCreditAwardEntity(distributeAwardEntity.getUserId(), creditAmount);

        GiveOutPrizesAggregate giveOutPrizesAggregate = new GiveOutPrizesAggregate();
        giveOutPrizesAggregate.setUserId(distributeAwardEntity.getUserId());
        giveOutPrizesAggregate.setUserAwardRecordEntity(userAwardRecordEntity);
        giveOutPrizesAggregate.setUserCreditAwardEntity(userCreditAwardEntity);

        // 存储发奖对象
        repository.saveGiveOutPrizesAggregate(giveOutPrizesAggregate);
    }

    private Float generateRandom(Float min, Float max) {
        if (min.equals(max)) return min;
        float randomFloat = min + (float)(Math.random() * (max - min));
        return (float) Math.round(randomFloat * 100f) / 100f;
    }
}
